package com.moonbird.springboot.Utils;

import com.alibaba.dashscope.audio.asr.recognition.Recognition;
import com.alibaba.dashscope.audio.asr.recognition.RecognitionParam;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public final class AudioTranscriptionUtils {

    private static final String API_KEY = "sk-c91bee81e9ef4fd4abe43a61b8f38479";

    private AudioTranscriptionUtils() {
        throw new AssertionError("Utility class should not be instantiated.");
    }

    /**
     * Transcribes the given audio file.
     *
     * @param audioFile the audio file to transcribe
     * @return the transcribed text
     */
    public static String transcribeAudio(File audioFile) {
        // Create Recognition instance
        Recognition recognizer = new Recognition();
        // Create RecognitionParam
        RecognitionParam param = RecognitionParam.builder()
                .model("paraformer-realtime-v2")
                .format("wav")
                .sampleRate(16000)
                .apiKey(API_KEY)
                .build();

        try {
            String result = recognizer.call(param, audioFile);
            JSONObject jsonObject = JSON.parseObject(result);
            String text = jsonObject.getJSONArray("sentences").getJSONObject(0).getString("text");
            return text;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}